package com.zone.vehicle.superapp.view.login.secret;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.module.account.entity.CaptchaGetEntity;
import com.zone.sdk.module.account.entity.CheckCaptchaEntity;
import com.zone.sdk.module.account.entity.LoginEntity;
import com.zone.sdk.module.account.entity.LoginStatusEntity;
import com.zone.sdk.module.account.entity.QrLoginEntity;
import com.zone.sdk.module.account.entity.QrLoginPollEntity;
import com.zone.sdk.module.account.entity.UserInfoEntity;
import com.zone.vehicle.lib.view.captcha.model.CaptchaGetIt;
import com.zone.vehicle.lib.view.captcha.widget.BlockPuzzleDialog;
import com.zone.vehicle.lib.view.captcha.widget.DragImageView;
import com.zone.vehicle.superapp.databinding.FragmentLoginSecretBinding;
import com.zone.vehicle.superapp.model.LoginViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.utils.PhoneUtils;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Timer;
import java.util.TimerTask;

import static com.zone.vehicle.superapp.view.login.LoginFragment.FIRST_SET_SECRET_FRAGMENT;
import static com.zone.vehicle.superapp.view.login.LoginFragment.FORGET_SECRET_FRAGMENT;
import static com.zone.vehicle.superapp.view.login.LoginFragment.LOGIN_MESSAGE_FRAGMENT;

public class LoginSecretFragment extends BaseFragment {

    private LoginViewModel viewModel;
    private FragmentLoginSecretBinding binding;
    private BlockPuzzleDialog blockPuzzleDialog;

    Timer timer = null;
    private static final int DELAY = 1000;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FragmentLoginSecretBinding.inflate(inflater, container, false);
        viewModel = new ViewModelProvider(this, new ViewModelFactory())
                .get(LoginViewModel.class);
        blockPuzzleDialog = new BlockPuzzleDialog(this.requireContext());
        return binding.getRoot();
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (ObjectUtils.isNotEmpty(result) && StringUtils.isNotEmpty(result.getResultMsg())) {
                    showLoginFailed(result.getResultMsg());
                }
            }
        });
        blockPuzzleDialog.setDragListener(new DragImageView.DragListenner() {
            @Override
            public void onDrag(double position) {
                CaptchaGetEntity entity = viewModel.getCaptchaGet().getValue();
                if (ObjectUtils.isNotEmpty(entity)){
                    viewModel.checkCaptcha(position, entity.getToken(), entity.getSecretKey());
                }
            }
        });

        viewModel.getCaptchaGet().observe(getViewLifecycleOwner(), new Observer<CaptchaGetEntity>() {
            @Override
            public void onChanged(CaptchaGetEntity captchaGetEntity) {
                if (ObjectUtils.isNotEmpty(captchaGetEntity)){
                    binding.loading.setVisibility(View.GONE);
                    CaptchaGetIt data = new CaptchaGetIt();
                    data.setJigsawImageBase64(captchaGetEntity.getJigsawImageBase64());
                    data.setOriginalImageBase64(captchaGetEntity.getOriginalImageBase64());
                    data.setSecretKey(captchaGetEntity.getSecretKey());
                    data.setToken(captchaGetEntity.getToken());
                    blockPuzzleDialog.setData(data);
                    blockPuzzleDialog.show();
                }
            }
        });
        viewModel.getCheckCaptcha().observe(getViewLifecycleOwner(), new Observer<CheckCaptchaEntity>() {
            @Override
            public void onChanged(CheckCaptchaEntity checkCaptchaEntity) {
                if (ObjectUtils.isEmpty(checkCaptchaEntity)){
                    blockPuzzleDialog.resetCheck();
                    viewModel.captchaGet();
                }
            }
        });
        viewModel.getCaptcha_certificate().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (StringUtils.isNotEmpty(s)){
                    blockPuzzleDialog.ok();
                    blockPuzzleDialog.cancel();
                    login();
                }else {
                    viewModel.captchaGet();
                }
            }
        });

        viewModel.getLoginEntity().observe(getViewLifecycleOwner(), new Observer<LoginEntity>() {
            @Override
            public void onChanged(LoginEntity loginEntity) {
                if (ObjectUtils.isNotEmpty(loginEntity)){
                    if (loginEntity.getFirst_login() == 2){
                        changePage(FIRST_SET_SECRET_FRAGMENT);
                    } else {
                        viewModel.queryUserInfo(requireContext());
                    }
                }
            }
        });
        viewModel.getUserInfo().observe(getViewLifecycleOwner(), new Observer<UserInfoEntity>() {
            @Override
            public void onChanged(UserInfoEntity userInfoEntity) {
                finish();
            }
        });
        binding.btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        binding.reSetSecret.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePage(FORGET_SECRET_FRAGMENT);
            }
        });

        binding.btnCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePage(LOGIN_MESSAGE_FRAGMENT);
            }
        });
        viewModel.getQrCode().observe(getViewLifecycleOwner(), new Observer<QrLoginEntity>() {
            @Override
            public void onChanged(QrLoginEntity entity) {
                if (ObjectUtils.isEmpty(entity) || StringUtils.isEmpty(entity.getLogin_url())){
                    return;
                }
                try {
                    binding.qrCode.setImageBitmap(new BarcodeEncoder().encodeBitmap(entity.getLogin_url(), BarcodeFormat.QR_CODE, 308,308));
                } catch (WriterException e) {
                    e.printStackTrace();
                };
            }
        });
        viewModel.getLoginStatusEntityMutableLiveData().observe(getViewLifecycleOwner(), new Observer<LoginStatusEntity>() {
            @Override
            public void onChanged(LoginStatusEntity loginStatusEntity) {
                stopPollLoginStatus();
                showToast("登录成功！");
                finish();
            }
        });

        binding.btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkPhone(binding.phone.getText().toString())) {
                    String pwd = binding.pwd.getText().toString();
                    if (!checkPwd(pwd)){
                        return;
                    }
                    binding.loading.setVisibility(View.VISIBLE);
                    viewModel.captchaGet();
                    viewModel.getPhone().setValue(binding.phone.getText().toString());
                }
            }
        });

        viewModel.getQrLoginPollEntity().observe(getViewLifecycleOwner(), new Observer<QrLoginPollEntity>() {
            @Override
            public void onChanged(QrLoginPollEntity qrLoginPollEntity) {
                if (ObjectUtils.isNotEmpty(qrLoginPollEntity)){
                    if (qrLoginPollEntity.getStatus() == 3) {
                        QrLoginPollEntity.Token token = qrLoginPollEntity.getToken();
                        viewModel.cacheLogin(getContext(), token);
                        viewModel.queryUserInfo(getContext());
                    }else {

                    }
                }
            }
        });

        viewModel.getUserInfo().observe(getViewLifecycleOwner(), new Observer<UserInfoEntity>() {
            @Override
            public void onChanged(UserInfoEntity userInfoEntity) {
                if (ObjectUtils.isNotEmpty(userInfoEntity)) {
                    finish();
                }
            }
        });

    }

    private void startPollLoginStatus(){
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                viewModel.qrLoginPolling();
            }
        }, DELAY, DELAY);
    }

    private void stopPollLoginStatus(){
        timer.cancel();
    }


    private void login(){
        String phone = binding.phone.getText().toString();
        String pwd = binding.pwd.getText().toString();
        if (!checkPwd(pwd)){
            return;
        }
        if(StringUtils.isNotEmpty(phone) && StringUtils.isNotEmpty(pwd)){
            viewModel.login(requireContext(), phone, pwd);
        }else {
            showToast("请输入用户名和密码");
        }
    }

    private boolean checkPhone(String phone){
        if (!PhoneUtils.isPhoneNum(phone)){
            Toast.makeText(
                    requireContext(),
                    "请输入手机号码",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        viewModel.getRemoteQrCode(requireContext());
        startPollLoginStatus();
    }

    @Override
    public void onPause() {
        super.onPause();
        clean();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void finish(){
        requireActivity().finish();
    }

    private void clean(){
        viewModel.getError().setValue(null);
        stopPollLoginStatus();
    }

}